package cn.sciento.boot.transfer.handler;

import io.choerodon.mybatis.domain.EntityTable;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import cn.sciento.boot.data.change.dto.ChangeData;
import cn.sciento.boot.data.change.handler.DataChangeBaseHandler;
import cn.sciento.boot.transfer.app.service.ProducerEventService;
import cn.sciento.boot.transfer.domain.entity.ProducerEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class DataTansferHandler extends DataChangeBaseHandler {
  @Autowired
  private ProducerEventService producerEventService;
  
  public final ThreadLocal<List<ProducerEvent>> EVENT_RECORD = new ThreadLocal<>();
  
  private static final Logger logger = LoggerFactory.getLogger(DataTansferHandler.class);
  
  public Boolean canProcess(EntityTable table) {
    return this.producerEventService.existProducerConfig(table.getName());
  }
  
  protected void doProcess(EntityTable table, List<ChangeData> changeDataList) {
    try {
      List<ProducerEvent> producerEvents = this.producerEventService.addProducerEvent(changeDataList);
      if (CollectionUtils.isEmpty(producerEvents)) {
        return;
      }
      if (null != this.EVENT_RECORD.get()) {
        producerEvents.addAll(this.EVENT_RECORD.get());
      }
      this.EVENT_RECORD.set(producerEvents);
    } catch (Exception e) {
      logger.info("Errors occurred during the data distribution process", e);
      throw e;
    } 
  }
  
  public void doCommit() {
    try {
      List<ProducerEvent> eventIdList = this.EVENT_RECORD.get();
      if (CollectionUtils.isNotEmpty(eventIdList)) {
        eventIdList.forEach(item -> this.producerEventService.sentProducerEvent(item));
      }
    } finally {
      this.EVENT_RECORD.remove();
    } 
  }
}
